//
//  TaskManagerViewController.m
//  MyProject
//
//  Created by Pei on 16/6/22.
//  Copyright © 2016年 Xiaobo Pei. All rights reserved.
//

#import "TaskManagerViewController.h"
#import "IHRefreshTableView.h"
#import "TaskManagerCell.h"
//#import "EditTaskViewController.h"
#import "CreateTaskViewController.h"
#import "NSMutableArray+Additions.h"
#import "UserInfo.h"
#import "SelectModel.h"
#import "ManagerTaskViewController.h"
#import "RequestPostUploadHelper.h"

@interface TaskManagerViewController ()<UITableViewDataSource,UITableViewDelegate,IHTableViewRefreshingDelegate>
{
    MySceneType _type;
    
    IHRefreshTableView *_myTable;
    
    UIView *_addView;
    
    UIControl *_addControl;
    
    UIButton *_rightBtn;
    
    NSArray *_contentArray;
    
    NSString *TMP_UPLOAD_IMG_PATH;
    
    NSMutableArray *sucessArray;
}

@end

@implementation TaskManagerViewController

- (id)initWith:(MySceneType)type
{
    self = [super init];
    if (self)
    {
        _type = type;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:Hide_TabBar_Notification object:nil];
    
    //_selFlags = [[NSMutableArray alloc] initWithCapacity:3];
    _contentArray = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:Create_Task];
    //    for (int i = 0; i < _contentArray.count; i++)
    //    {
    //        [_selFlags addObject:[NSNumber numberWithBool:NO]];
    //    }
    
    [_myTable reloadData];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:Hide_TabBar_Notification object:nil];
    
}

- (void)viewDidLoad {
    
    switch (_type) {
        case MySceneToBeCheck:
        {
            self.navTitle = @"待检查";
        }
            break;
        case MySceneToBeSure:
        {
            self.navTitle = @"待确认";
        }
            break;
        case MySceneToBeChange:
        {
            self.navTitle = @"待整改";
        }
            break;
        case MySceneToBeReviewed:
        {
            self.navTitle = @"待审核";
        }
            break;
            
        default:
            break;
    }
    
    [super viewDidLoad];
    
    sucessArray = [[NSMutableArray alloc] initWithCapacity:3];
    
    TMP_UPLOAD_IMG_PATH = @"";
    
    _rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 22)];
    //[rightBtn setBackgroundImage:[UIImage imageNamed:@"02edit"] forState:UIControlStateNormal];
    //[rightBtn setBackgroundImage:[UIImage imageNamed:@"02edit"] forState:UIControlStateHighlighted];
    [_rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [_rightBtn setTitleColor:kBlueColor forState:UIControlStateNormal];
    _rightBtn.titleLabel.font = kAppFont(Home_Big_Size);
    [_rightBtn addTarget:self action:@selector(rightBtnAcion) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
    
    
    
    [self initTableView];
    
    _addControl = [[UIControl alloc] init];
    _addControl.frame = CGRectMake(0.0f, kDeviceHeight-NAV_HEIGHT-kTabHeight, kDeviceWidth, kTabHeight);
    [_addControl addTarget:self action:@selector(addControlAction) forControlEvents:UIControlEventTouchUpInside];
    _addControl.backgroundColor = kBtnBackgroundColor;
    [self.view addSubview:_addControl];
    
    //02edit@3x
    UILabel *btnTitle = [[UILabel alloc] initWithFrame:CGRectMake((kDeviceWidth-66)/2.0f, (_addControl.height-Home_Big_Size)/2.0f, 66, Home_Big_Size)];
    btnTitle.textColor = kWhiteColor;
    btnTitle.text = @"添加任务";
    btnTitle.font = kAppFont(Home_Big_Size);
    [_addControl addSubview:btnTitle];
    
    _addView = [[UIView alloc] init];
    _addView.hidden = YES;
    _addView.frame = CGRectMake(0.0f, kDeviceHeight-NAV_HEIGHT-kTabHeight, kDeviceWidth, kTabHeight);
    [self.view addSubview:_addView];
    
    //114 122 162
    UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancleBtn.frame = CGRectMake(0.0f, 0.0f, kDeviceWidth/3.0f, kTabHeight);
    [cancleBtn setBackgroundColor:kRGB(114, 122, 162)];
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    cancleBtn.titleLabel.font = kAppFont(Home_Big_Size);
    cancleBtn.tag = 116;
    [cancleBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_addView addSubview:cancleBtn];
    
    UIButton *uploadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    uploadBtn.frame = CGRectMake(kDeviceWidth/3.0f, 0.0f, kDeviceWidth/3.0f, kTabHeight);
    [uploadBtn setBackgroundColor:kBtnBackgroundColor];
    [uploadBtn setTitle:@"提交" forState:UIControlStateNormal];
    [uploadBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    uploadBtn.titleLabel.font = kAppFont(Home_Big_Size);
    [uploadBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    uploadBtn.tag = 118;
    [_addView addSubview:uploadBtn];
    
    
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(kDeviceWidth/3.0f*2.0f, 0.0f, kDeviceWidth/3.0f, kTabHeight);
    [deleteBtn setBackgroundColor:kRedColor];
    [deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    [deleteBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    deleteBtn.titleLabel.font = kAppFont(Home_Big_Size);
    deleteBtn.tag = 119;
    [deleteBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_addView addSubview:deleteBtn];
}

#pragma mark **************************** UI *********************************
- (void)initTableView
{
    CGRect frame = CGRectMake(0, 0.0f, kDeviceWidth, kDeviceHeight-NAV_HEIGHT-kTabHeight);
    _myTable = [[IHRefreshTableView alloc] initWithFrame:frame refreshType:-1 andAutoLoad:NO];
    _myTable.delegate = self;
    _myTable.dataSource = self;
    _myTable.refreshDelegate = self;
    _myTable.footer.hidden = YES;
    _myTable.header.hidden = YES;
    _myTable.allowsSelectionDuringEditing = YES;
    [self.view addSubview:_myTable];
}

#pragma mark ************************** Action ************************
- (void)rightBtnAcion
{
    [_myTable setEditing:!_myTable.editing animated:YES];
    
    _addControl.hidden = YES;
    _addView.hidden = NO;
    
    [self.navigationItem setRightBarButtonItem:nil];
}

- (void)addControlAction
{
    CreateTaskViewController *createTaskVC = [[CreateTaskViewController alloc] init];
    [self.navigationController pushViewController:createTaskVC animated:YES];
}


- (void)btnAction:(UIButton*)sender
{
    switch (sender.tag) {
        case 116:
        {
            [_myTable setEditing:!_myTable.editing animated:YES];
            
            _addView.hidden = YES;
            _addControl.hidden = NO;
            
            [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
        }
            break;
        case 119:
        {
            NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:_contentArray];
            for (int i = 0; i < _contentArray.count; i++)
            {
                NSDictionary *tempD = [_contentArray objectAtIndex:i];
                if ([[tempD valueForKey:@"isSelect"] boolValue]) {
                    //[tempArray replaceObjectAtIndex:i withObject:@""];
                    [tempArray removeObject:tempD];
                }
            }
            _contentArray = tempArray;
            
            [[NSUserDefaults standardUserDefaults] setObject:_contentArray forKey:Create_Task];
            _contentArray = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:Create_Task];
            
            [_myTable reloadData];
            
            [_myTable setEditing:!_myTable.editing animated:YES];
            
            _addView.hidden = YES;
            _addControl.hidden = NO;
            
            [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
        }
            break;
        case 118:
        {
            [[YMUIUtil getInstance] hideLoadingView];
            [[YMUIUtil getInstance] showLoadingWithTitle:@"加载中..."];
            
            [sucessArray removeAllObjects];
            
            [self performSelector:@selector(uploadTestAction) withObject:nil afterDelay:1.0f];
            
            
            
        }
            break;
        default:
            break;
    }
}

- (void)uploadTestAction{
    

    NSMutableArray *tempArrayVVVV = [[NSMutableArray alloc] initWithArray:_contentArray];
    
    if (tempArrayVVVV == nil || tempArrayVVVV.count <= 0) {
        [[YMUIUtil getInstance] hideLoadingView];
    }else{
        BOOL isSelect = NO;
        for (int i = 0; i < _contentArray.count; i++)
        {
            NSDictionary *tempD = [_contentArray objectAtIndex:i];
            if ([[tempD valueForKey:@"isSelect"] boolValue]){
                isSelect = YES;
            }
        }
        
        if (isSelect) {
            [[YMUIUtil getInstance] hideLoadingView];
        }
    }
    
    //[self loadingView];
    for (int i = 0; i < _contentArray.count; i++)
    {
        NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:_contentArray];
        
        NSDictionary *tempD = [_contentArray objectAtIndex:i];
        if ([[tempD valueForKey:@"isSelect"] boolValue]) {
            
            
            //NSDictionary *tempDic = tempD;
            NSArray *InspectionItemsAry = [tempD objectForKey:@"InspectionItems"];
            
            BOOL isHas = NO;
            
            for (NSDictionary *tempD in InspectionItemsAry) {
                
                NSArray *attachAry = [tempD objectForKey:@"InspectContentList"];
                
                
                for (NSDictionary *attachDic in attachAry) {
                    NSDictionary *RiskLevel_Dic;
                    if ([attachDic objectForKey:@"RiskLevel_Dic"] != nil) {
                        RiskLevel_Dic = [attachDic objectForKey:@"RiskLevel_Dic"];
                    }else{
                        RiskLevel_Dic = nil;
                    }
                    
                    NSArray *imageAry;
                    if ([attachDic objectForKey:@"ImageData_List"] != nil) {
                        imageAry = [attachDic objectForKey:@"ImageData_List"];
                    }else{
                        imageAry = nil;
                    }
                    NSString *miaoShuStr = [attachDic valueForKey:@"JianChaMiaoShu"];
                    if ([attachDic valueForKey:@"JianChaMiaoShu"] != nil && miaoShuStr.length > 0) {
                        miaoShuStr = [attachDic valueForKey:@"JianChaMiaoShu"];
                    }else{
                        miaoShuStr = @"";
                    }
                    
                    
                    if (([attachDic valueForKey:@"KouFen"] != nil && [[attachDic valueForKey:@"KouFen"] intValue] > 0) && ([attachDic objectForKey:@"RiskLevel_Dic"] != nil && RiskLevel_Dic.count >0) && (imageAry != nil && imageAry.count >0) && (miaoShuStr != nil && miaoShuStr.length > 0)) {
                        isHas = YES;
                    }
                }
            }
            
            if (!isHas) {
                [[YMUIUtil getInstance] hideLoadingView];
                [self performSelector:@selector(showTipViewAutoDis) withObject:nil afterDelay:0.5f];
                return;
            }
            
            
            [[YMUIUtil getInstance] hideLoadingView];
            [[YMUIUtil getInstance] showLoadingWithTitle:@"加载中..."];
            
            NSMutableArray *InspectTaskListArray = [[NSMutableArray alloc] initWithCapacity:3];
            NSArray *tempA = [tempD objectForKey:@"InspectionItems"];
            for (NSDictionary *ddd in tempA) {
                NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:3];
                [dic setValue:[ddd valueForKey:@"InspectItemCode"] forKey:@"InspectItemCode"];
                
                
                //NSDateFormatter *JZdateFormatter = [[NSDateFormatter alloc] init];
                //[JZdateFormatter setDateFormat:@"yyyy-MM-dd"];
                //NSDate *JZdate = [JZdateFormatter dateFromString:[tempD valueForKey:@"JieZhiDate"]];
                
                //[dic setObject:[ddd valueForKey:@"JieZhiDate"] forKey:@"DeadLineDate"];//逾期整改时间
                
                
                
                NSArray *pointA = [ddd objectForKey:@"InspectContentList"];
                NSDictionary *toGetDate = [pointA objectAtIndex:0];
                
                NSString *customName = [toGetDate valueForKey:@"InspectTaskNameCustom"];
                if (customName == nil || customName.length <= 0) {
                    customName = @"";
                }
                [dic setValue:customName forKey:@"InspectTaskName"];
                
                NSString *strD = [toGetDate valueForKey:@"JieZhiDate"];
                if (strD == nil || strD.length <= 0) {
                    strD = @"";
                }
                [dic setObject:strD forKey:@"DeadLineDate"];//逾期整改时间
                
                NSMutableArray *ppp = [[NSMutableArray alloc] initWithCapacity:3];
                [ppp removeAllObjects];
                for (NSDictionary *aaa in pointA) {
                    
                    NSArray *imageList = [aaa objectForKey:@"ImageData_List"];
                    
                    NSMutableArray *idList = [[NSMutableArray alloc] initWithCapacity:3];
                    [idList removeAllObjects];
                    
                    for (int j = 0; j < imageList.count; j ++) {
                        
                        //[hImageView setImage:tempImage];
                        NSLog(@"===TMP_UPLOAD_IMG_PATH===%@",TMP_UPLOAD_IMG_PATH);
                        NSData* imageData = [imageList objectAtIndex:j];//UIImagePNGRepresentation(tempImage);
                        
                        NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
                        
                        NSString* documentsDirectory = [paths objectAtIndex:0];
                        
                        // Now we get the full path to the file
                        
                        NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",[self generateUuidString],@".jpg"]];
                        
                        // and then we write it out
                        TMP_UPLOAD_IMG_PATH=fullPathToFile;
                        NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];
                        NSLog(@"===new fullPathToFile===%@",fullPathToFile);
                        NSLog(@"===new FileName===%@",[nameAry objectAtIndex:[nameAry count]-1]);
                        
                        [imageData writeToFile:fullPathToFile atomically:NO];
                        
                        //[self onPostData];
                        
                        NSMutableDictionary * dir=[NSMutableDictionary dictionaryWithCapacity:7];
                        //[dir setValue:@"save" forKey:@"m"];
                        [dir setValue:[[UserInfo getInstance] getUserID] forKey:@"UserID"];
                        [dir setValue:[[UserInfo getInstance] getUseToken] forKey:@"UserToken"];
                        NSString *url= kAppApi(Upload_File);
                        NSLog(@"=======上传%@", url);
                        if([TMP_UPLOAD_IMG_PATH isEqualToString:@""]){
                            [RequestPostUploadHelper postRequestWithURL:url postParems:dir picFilePath:nil picFileName:nil];
                        }else{
                            NSLog(@"有图标上传");
                            NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];
                            NSString *result =  [RequestPostUploadHelper postRequestWithURL:url postParems:dir picFilePath:TMP_UPLOAD_IMG_PATH picFileName:[nameAry objectAtIndex:[nameAry count]-1]];
                            NSDictionary *resultDic = [self dictionaryWithJsonString:result];
                            
                            
                            NSArray *imageID = [resultDic objectForKey:@"ResourcesList"];
                            for (NSDictionary *ggg in imageID) {
                                [idList addObject:[NSNumber numberWithInt:[[ggg valueForKey:@"ResourceId"] intValue]]];
                            }
                        }
                    }
                    
                    
                    NSMutableDictionary *tttt = [[NSMutableDictionary alloc] initWithCapacity:3];
                    if ([[aaa valueForKey:@"KouFen"] intValue] > 0) {
                        /*
                         "RiskLevel": 0,
                         "RiskDesc":  "问题描述",
                         "InspectContentID": 1,
                         "Points": 2,
                         "AttachIDList": [
                         
                         */
                        int kkk = [[aaa valueForKey:@"KouFen"] intValue];
                        NSDictionary *yyy = [aaa objectForKey:@"RiskLevel_Dic"];
                        [tttt setValue:[yyy valueForKey:@"Value"] forKey:@"RiskLevel"];
                        [tttt setValue:[aaa valueForKey:@"JianChaMiaoShu"] forKey:@"RiskDesc"];
                        [tttt setValue:[aaa valueForKey:@"InspectContentID"] forKey:@"InspectContentID"];
                        [tttt setValue:[NSNumber numberWithInt:kkk] forKey:@"Points"];
                        //[tttt setObject:[aaa objectForKey:@"ImageData_List"] forKey:@"AttachIDList"];
                        [tttt setObject:idList forKey:@"AttachIDList"];
                        
                        [ppp addObject:tttt];
                    }
                }
                
                [dic setObject:ppp forKey:@"RiskList"];
                
                [InspectTaskListArray addObject:dic];
            }
            
            
            
            
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            NSDate *date = [dateFormatter dateFromString:[tempD valueForKey:@"InspectDate"]];
            
            //UserID
            NSArray *tempPeiTongA = [tempD objectForKey:@"AccompanyPersonUIDsList"];
            NSMutableArray *peiTongArray = [[NSMutableArray alloc] initWithCapacity:3];
            [peiTongArray removeAllObjects];
            for (NSDictionary *peiTongTT in tempPeiTongA) {
                [peiTongArray addObject:[peiTongTT valueForKey:@"UserID"]];
            }
            //NSData *mmmm = [self toJSONData:peiTongArray];
            //NSString *jsonString = [[NSString alloc] initWithData:mmmm encoding:NSUTF8StringEncoding];
            
            //Upload_Task
            NSDictionary *bodyDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                     [[UserInfo getInstance] getUserID],@"UserID",//UserID
                                     [tempD valueForKey:@"InspectionNo"],@"InspectionNo", //检查单号
                                     [NSNumber numberWithInt:[[[tempD objectForKey:@"InspectType"] valueForKey:@"Value"] intValue]], @"InspectType", //检查类型 int  {Code = "SQCP_Security_InspectionType_Daily"; Name = "\U65e5\U5e38\U68c0\U67e5"; Value = 0;},
                                     //{"projectCode":"XM201611","orgCode":"YFZX","orgName":"公司本部","unitCode":"region","unitName":"三航局","projectName":"青岛项目部"}
                                     [[tempD objectForKey:@"InspectOrgAndProject"] valueForKey:@"unitCode"], @"InspectOrgCode", //被检查公司编码
                                     [[tempD objectForKey:@"InspectOrgAndProject"] valueForKey:@"projectCode"], @"InspectProjectCode", //被检查项目编码
                                     [tempD valueForKey:@"InspectDate"], @"InspectDate", //检查时间 DateTime
                                     [NSNumber numberWithInt:[[tempD valueForKey:@"InspectionState"] intValue]], @"InspectionState", //检查单状态 int
                                     
                                     [tempD valueForKey:@"InspectionRemark"], @"InspectionRemark", //检查单备注
                                     //@"KKKKKK", @"InspectionRemark", //检查单备注
                                     
                                     InspectTaskListArray,@"InspectTaskList",
                                     peiTongArray,@"AccompanyPersonUIDs",
                                     nil];
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            //[manager.requestSerializer setValue:[[UserInfo getInstance] getUseToken] forHTTPHeaderField:@"UserToken"];
            //[manager.requestSerializer setValue:[[UserInfo getInstance] getUserID] forHTTPHeaderField:@"UserUid"];
            
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            [manager.requestSerializer setValue:[[UserInfo getInstance] getUseToken] forHTTPHeaderField:@"UserToken"];
            [manager.requestSerializer setValue:[[UserInfo getInstance] getUserID] forHTTPHeaderField:@"UserUid"];
            [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
            
            
            NSString *urlStr = [NSString stringWithFormat:@"%@",kAppApi(Upload_Task)];
            urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSLog(@"url =  %@", urlStr);
            NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithDictionary:bodyDic];
            NSLog(@"bodybodybody====%@", [tempDic description]);
            
            [manager POST:urlStr parameters:tempDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *jsonDict = [YMUtil changeType:(NSDictionary*)responseObject];
                NSLog(@"获取到的数据为：%@",jsonDict);
                if ([[YMNetDataUtil getSuccessState:jsonDict] intValue] == 1){
                    //[tempArray removeObject:tempD];
                    [sucessArray addObject:tempD];
                }
                
                //_contentArray = tempArray;
                
                //[[NSUserDefaults standardUserDefaults] setObject:_contentArray forKey:Create_Task];
                //_contentArray = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:Create_Task];
                
                NSMutableArray *MMMMM = [[NSMutableArray alloc] initWithArray:_contentArray];
                for (NSDictionary *hhhh in sucessArray) {
                    [MMMMM removeObject:hhhh];
                }
                
                _contentArray = MMMMM;
                
                [[NSUserDefaults standardUserDefaults] setObject:_contentArray forKey:Create_Task];
                _contentArray = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:Create_Task];
                
                [_myTable reloadData];
                
                if ([[YMNetDataUtil getSuccessState:jsonDict] intValue] == 0)
                {
                    [[YMUIUtil getInstance] showTipViewAutoDis:@"提交失败"];
                }
                
                NSLog(@"========error%@",[jsonDict valueForKey:@"Error"]);
                [[YMUIUtil getInstance] hideLoadingView];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"发生错误！%@",error);
                [[YMUIUtil getInstance] hideLoadingView];
            }];
            
            
        }
    }
    /*
    _contentArray = tempArray;
    
    [[NSUserDefaults standardUserDefaults] setObject:_contentArray forKey:Create_Task];
    _contentArray = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:Create_Task];
     */
    
    [_myTable setEditing:!_myTable.editing animated:YES];
    
    _addView.hidden = YES;
    _addControl.hidden = NO;
    
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
    
    
    
    
    
    
}

- (void)showTipViewAutoDis{
    [[YMUIUtil getInstance] showTipViewAutoDis:@"待完善检查单不能上传"];
}


// 将字典或者数组转化为JSON串
- (NSData *)toJSONData:(id)theData{
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    if ([jsonData length] > 0 && error == nil){
        return jsonData;
    }else{
        return nil;
    }
}

//- (void)uploadTask:(NSDictionary*)tempD
//{
//    NSMutableArray *InspectTaskListArray = [[NSMutableArray alloc] initWithCapacity:3];
//    NSArray *tempA = [tempD objectForKey:@"InspectionItems"];
//    for (NSDictionary *tempD in tempA) {
//        NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:3];
//        [dic setValue:[tempD valueForKey:@"InspectContentID"] forKey:@"InspectItemCode"];
//        [dic setValue:[tempD valueForKey:@"InspectContentName"] forKey:@"InspectTaskName"];
//        [dic setValue:@"" forKey:@"DeadLineDate"];
//        [InspectTaskListArray addObject:dic];
//    }
//    
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"yyyy:MM:dd HH:mm:ss"];
//    NSDate *date = [dateFormatter dateFromString:[tempD valueForKey:@"InspectDate"]];
//    
//    //Upload_Task
//    NSDictionary *bodyDic = [NSDictionary dictionaryWithObjectsAndKeys:
//                             [[UserInfo getInstance] getUserID],@"UserID",//UserID
//                             [tempD valueForKey:@"InspectionNo"],@"InspectionNo", //检查单号
//                             [NSNumber numberWithInt:[[[tempD objectForKey:@"InspectType"] valueForKey:@"Value"] intValue]], @"InspectType", //检查类型 int  {Code = "SQCP_Security_InspectionType_Daily"; Name = "\U65e5\U5e38\U68c0\U67e5"; Value = 0;},
//                             //{"projectCode":"XM201611","orgCode":"YFZX","orgName":"公司本部","unitCode":"region","unitName":"三航局","projectName":"青岛项目部"}
//                             [[tempD objectForKey:@"InspectOrgAndProject"] valueForKey:@"orgCode"], @"InspectOrgCode", //被检查公司编码
//                             [[tempD objectForKey:@"InspectOrgAndProject"] valueForKey:@"projectCode"], @"InspectProjectCode", //被检查项目编码
//                             date, @"InspectDate", //检查时间 DateTime
//                             [NSNumber numberWithInt:[[tempD valueForKey:@"InspectionState"] intValue]], @"InspectionState", //检查单状态 int
//                             InspectTaskListArray,@"InspectTaskList",
//                             @"",@"AccompanyPersonUIDs",//陪同人员UserID列表
//                             [tempD valueForKey:@"InspectionRemark"], @"InspectionRemark", //检查单备注
//                             nil];
//    [[YMNetLib getInstance] connectWithAction:Upload_Task method:@"POST" withContent:nil withBody:bodyDic withDelegate:self];
//    
//}

- (void)NetDoOverSuccess:(NSDictionary*)body
{
    //    if ([[YMNetDataUtil getSuccessState:body] intValue] == 1)
    //    {
    //        NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:_contentArray];
    //        for (int i = 0; i < _contentArray.count; i++)
    //        {
    //            NSDictionary *tempD = [_contentArray objectAtIndex:i];
    //            if ([[tempD valueForKey:@"InspectionNo"] boolValue]) {
    //                //[tempArray replaceObjectAtIndex:i withObject:@""];
    //                [self uploadTask:tempD];
    //                [tempArray removeObject:tempD];
    //            }
    //        }
    //        [_myTable reloadData];
    //    }
    
    NSLog(@"========error%@",[body valueForKey:@"Error"]);
}


#pragma mark  ************************* UITableViewDataSource **************************************
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return (nil == _contentArray) ? 0 : _contentArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"TaskManagerCell";
    /*
     TaskManagerCell *cell = (TaskManagerCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
     if (cell == nil)
     {
     cell = [[TaskManagerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
     }
     cell.selectionStyle = UITableViewCellSelectionStyleNone;
     [cell showWithData:nil];
     return cell;
     */
    TaskManagerCell *cell = (TaskManagerCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[TaskManagerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundView = [[UIView alloc] init];
    }
    NSDictionary *tempDic = [_contentArray objectAtIndex:indexPath.row];
    cell.mSelected = [(NSNumber *)[tempDic objectForKey:@"isSelect"] boolValue];
    //cell.textLabel.text = [NSString stringWithFormat:@"Row %ld", (long)indexPath.row];
    
    
    NSArray *InspectionItemsAry = [tempDic objectForKey:@"InspectionItems"];
    
    BOOL isHas = NO;
    
    for (NSDictionary *tempD in InspectionItemsAry) {
        
        NSArray *attachAry = [tempD objectForKey:@"InspectContentList"];
        
        
        for (NSDictionary *attachDic in attachAry) {
            NSDictionary *RiskLevel_Dic;
            if ([attachDic objectForKey:@"RiskLevel_Dic"] != nil) {
                RiskLevel_Dic = [attachDic objectForKey:@"RiskLevel_Dic"];
            }else{
                RiskLevel_Dic = nil;
            }
            
            NSArray *imageAry;
            if ([attachDic objectForKey:@"ImageData_List"] != nil) {
                imageAry = [attachDic objectForKey:@"ImageData_List"];
            }else{
                imageAry = nil;
            }
            
            NSString *miaoShuStr = [attachDic valueForKey:@"JianChaMiaoShu"];
            if ([attachDic valueForKey:@"JianChaMiaoShu"] != nil && miaoShuStr.length > 0) {
                miaoShuStr = [attachDic valueForKey:@"JianChaMiaoShu"];
            }else{
                miaoShuStr = @"";
            }

            
            if (([attachDic valueForKey:@"KouFen"] != nil && [[attachDic valueForKey:@"KouFen"] intValue] > 0) && ([attachDic objectForKey:@"RiskLevel_Dic"] != nil && RiskLevel_Dic.count >0) && (imageAry != nil && imageAry.count >0)  && (miaoShuStr != nil && miaoShuStr.length > 0) ) {
                isHas = YES;
            }
        }
    }
    
    
    [cell showWithData:tempDic];
    
    
    
    NSDictionary *InspectTypeDic = [tempDic objectForKey:@"InspectType"];
    
    NSArray *tempArray = [[NSUserDefaults standardUserDefaults] objectForKey:Check_Type_Items];
    for (NSDictionary *aaa in tempArray) {
        if ([[aaa valueForKey:@"Value"] intValue] == [[InspectTypeDic valueForKey:@"Value"] intValue])
        {
            if (isHas) {
                cell._statusLbl.text = [aaa objectForKey:@"Name"];
            }else{
                NSString *str = [NSString stringWithFormat:@"%@  %@", [aaa objectForKey:@"Name"], @"待完善"];
                NSString *firstStr = [aaa objectForKey:@"Name"];
                NSString *secondStr = @"  待完善";
                NSMutableAttributedString *kouMStr = [[NSMutableAttributedString alloc] initWithString:str];
                [kouMStr addAttribute:NSForegroundColorAttributeName value:kRedColor range:NSMakeRange(firstStr.length,secondStr.length)];
                cell._statusLbl.attributedText = kouMStr;
                
            }
            
            //cell._statusLbl.text = [aaa objectForKey:@"Name"];
        }
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    //[_selFlags moveObjectFromIndex:sourceIndexPath.row toIndex:destinationIndexPath.row];
}


#pragma mark -
#pragma mark Table view delegate

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.isEditing)
    {
        TaskManagerCell *cell = (TaskManagerCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        NSDictionary *tempDic = [_contentArray objectAtIndex:indexPath.row];
        /*
         NSArray *InspectionItemsAry = [tempDic objectForKey:@"InspectionItems"];
         
         BOOL isHas = NO;
         
         for (NSDictionary *tempD in InspectionItemsAry) {
         
         NSArray *attachAry = [tempD objectForKey:@"InspectContentList"];
         
         
         for (NSDictionary *attachDic in attachAry) {
         NSDictionary *RiskLevel_Dic;
         if ([attachDic objectForKey:@"RiskLevel_Dic"] != nil) {
         RiskLevel_Dic = [attachDic objectForKey:@"RiskLevel_Dic"];
         }else{
         RiskLevel_Dic = nil;
         }
         
         NSArray *imageAry;
         if ([attachDic objectForKey:@"ImageData_List"] != nil) {
         imageAry = [attachDic objectForKey:@"ImageData_List"];
         }else{
         imageAry = nil;
         }
         
         if (([attachDic valueForKey:@"KouFen"] != nil && [[attachDic valueForKey:@"KouFen"] intValue] > 0) && ([attachDic objectForKey:@"RiskLevel_Dic"] != nil && RiskLevel_Dic.count >0) && (imageAry != nil && imageAry.count >0)) {
         isHas = YES;
         }
         }
         }
         
         if (!isHas) {
         [[YMUIUtil getInstance] showTipViewAutoDis:@"待完善检查单不能上传"];
         return;
         }
         */
        [cell changeMSelectedState];
        
        
        
        //NSDictionary *tempDic = [_contentArray objectAtIndex:indexPath.row];
        NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:_contentArray];
        for (int i = 0; i < tempArray.count; i++)
        {
            NSMutableDictionary *tempD = [[NSMutableDictionary alloc] initWithDictionary:[tempArray objectAtIndex:i]];
            if ([[tempDic valueForKey:@"InspectionNo"] isEqualToString:[tempD valueForKey:@"InspectionNo"]]) {
                //[NSNumber numberWithBool:YES], @"isSelect"
                //[tempD setValue:@"1" forKey:@"isSelect"];
                //[tempD removeObjectForKey:@"isSelect"];
                [tempD setObject:[NSNumber numberWithBool:cell.mSelected] forKey:@"isSelect"];
                [tempArray replaceObjectAtIndex:i withObject:tempD];
            }
        }
        _contentArray = tempArray;
        
        //[_selFlags replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:cell.mSelected]];
    }
    else
    {
        NSDictionary *passDic = [_contentArray objectAtIndex:indexPath.row];
        ManagerTaskViewController *editVC = [[ManagerTaskViewController alloc] initWithData:passDic];
        [self.navigationController pushViewController:editVC animated:YES];
    }
}

- (NSString *)generateUuidString
{
    // create a new UUID which you own
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    
    // create a new CFStringRef (toll-free bridged to NSString)
    // that you own
    NSString *uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));
    
    // transfer ownership of the string
    // to the autorelease pool
    //[uuidString autorelease];
    
    // release the UUID
    CFRelease(uuid);
    
    return uuidString;
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
